<template>
  <div id="reg_ret_box">
    <div class="form-container">
      
      <div class="form-selector">
        <button :class="['selector-btn', { active: selectedForm === 'register' }]" @click="switchForm('register')">
          注册
        </button>
        <button :class="['selector-btn', { active: selectedForm === 'forgotPassword' }]" @click="switchForm('forgotPassword')">
          找回密码
        </button>
      </div>

    
      <div v-if="selectedForm === 'register'" class="register-form">
        <h2>注册</h2>
        <div v-for="field in registerFields" :key="field.id" class="form-group">
          <label :for="field.id">{{ field.label }}</label>
          <input :type="field.type" :id="field.id"  :autocomplete="field.autocomplete"   v-model="formData[field.id]" :placeholder="field.placeholder" />
        </div>
        <button class="submit-btn" @click="handleRegisterSubmit">提交注册</button>
      </div>

  
      <div v-if="selectedForm === 'forgotPassword'" class="forgot-password-form">
        <h2>找回密码</h2>
       
        <div v-if="currentStep === 1" class="step">
          <div class="form-group">
            <label for="account">账户</label>
            <input type="text" id="username" v-model="formData.username" placeholder="请输入要找回的账号" />
          </div>
          <button class="submit-btn" @click="goToNextStep">下一步</button>
        </div>
        
        <div v-if="currentStep === 2" class="step">
          <div class="form-group">
            <label for="email">邮箱</label>
            <input type="email" id="email" v-model="formData.email" placeholder="请输入注册邮箱" />
          </div>
          <button class="submit-btn" @click="goToNextStep">下一步</button>
          <button class="back-btn" @click="goToPreviousStep">上一步</button>
        </div>

      
        <div v-if="currentStep === 3" class="step">
          <div class="form-group">
            <label for="verificationCode">验证码</label>
            <input type="text" id="verificationCode" v-model="formData.verificationCode" placeholder="请输入验证码" />
          </div>
          <button class="submit-btn" @click="goToNextStep">下一步</button>
          <button class="back-btn" @click="goToPreviousStep">上一步</button>
        </div>

      
        <div v-if="currentStep === 4" class="step">
          <div class="form-group">
            <label for="newPassword">新密码</label>
            <input type="password" id="newPassword" v-model="formData.newPassword" placeholder="请输入新密码" />
          </div>
          <div class="form-group">
            <label for="confirmNewPassword">确认新密码</label>
            <input type="password" id="confirmNewPassword" v-model="formData.confirmNewPassword" placeholder="请再次输入新密码" />
          </div>
          <button class="submit-btn" @click="handleForgotPasswordSubmit">提交</button>
          <button class="back-btn" @click="goToPreviousStep">上一步</button>
        </div>
      </div>
    </div>
  </div>
  <CONFIRM    />
</template>

<script setup>
import { ref, reactive } from 'vue';
import { resetac, create_ac,get_VerificationCode ,judge_VerificationCode} from "../api/user.js"
import { success, warning } from '../static/js/alert.js';
import { useRouter } from 'vue-router';
import CONFIRM from '@/components/common/confirm.vue';

let VerificationCode=ref()
// 当前选择的表单类型
const selectedForm = ref('register');

// 找回密码的当前步骤
const currentStep = ref(1);

// 表单数据
const formData = reactive({
  username: undefined,
  password: undefined,
  confirmPassword: undefined,
  email: undefined,
  verificationCode: undefined,
  newPassword: undefined,
  confirmNewPassword: undefined,
});

// 注册表单字段
const registerFields = [
  { id: 'username', label: '用户名', type: 'text', placeholder: '请输入用户名' ,autocomplete:false},
  { id: 'password', label: '密码', type: 'password', placeholder: '请输入密码',autocomplete:false },
  { id: 'confirmPassword', label: '确认密码', type: 'password', placeholder: '请再次输入密码', autocomplete: false },
  { id: 'email', label: '邮箱', type: 'email', placeholder: '请输入邮箱', autocomplete: false },
];

// 切换表单类型
const switchForm = (formType) => {
  selectedForm.value = formType;
  currentStep.value = 1; // 重置步骤
  resetFormData(); // 重置表单数据
};

// 重置表单数据
const resetFormData = () => {
  Object.keys(formData).forEach((key) => {
    formData[key] = '';
  });
};

// 注册表单提交
const handleRegisterSubmit = async () => {
  if (!formData.username || !formData.password || !formData.confirmPassword) {
    warning("请填写完整表单")
    return;
  }
  if (formData.password !== formData.confirmPassword) {
    warning('两次输入的密码不一致');
    return;
    }
    const judge = await create_ac(formData.username, formData.password)
    if (judge == 1) { 
        success('您的账户是:' + formData.username +
            '\n' + "您的密码是:" + formData.password,5000);
        // 不采用直接给权证方案。手动登录。
    }
};

// 找回密码的下一步
const goToNextStep = async () => {
  if ((currentStep.value) === 1 && !formData.username) {
    warning('请输入要找回的账号');
    return;
  }
  if (currentStep.value === 2 && !formData.email) {
    warning('请输入邮箱');
    return;
  }
  if (currentStep.value === 2 && formData.email) {
    // 发送验证码
    const VerificationCode = await get_VerificationCode(formData.email, formData.username)
    if (VerificationCode) {
      
      const data = JSON.stringify({
        VerificationCode,
        date: Date.now(),
      })
      localStorage.setItem('VerificationCode', data)
    } else { 
      return 
    }
    // warning('验证码已发送到您的邮箱')

  }
  if (currentStep.value === 3 && !formData.verificationCode) {
    warning('请输入验证码');
    return;
  } 

  if (formData.verificationCode) {
    // 进行判断
    const id = JSON.parse(localStorage.getItem('VerificationCode')).VerificationCode.id;
    const timestamp = JSON.parse(localStorage.getItem('VerificationCode')).VerificationCode.date;
    const currentTimestamp = Date.now();
    const fiveMinutesInMilliseconds = 5 * 60 * 1000;
    const isExpired = currentTimestamp - timestamp > fiveMinutesInMilliseconds;
    if (isExpired) {
      // 时间戳过了5min失效
      warning("验证码已失效,请重新获取")
      return
    } else {
      const judge = await judge_VerificationCode(id, formData.verificationCode)
        if (judge == 1) {
        success('验证码正确')
      } else { 
        warning('验证码错误')
        return
      }
    }
  }   
 
  if (currentStep.value <= 3) {
    currentStep.value++;
  }
};

// 找回密码的上一步
const goToPreviousStep = () => {
  if (currentStep.value > 1) {
    currentStep.value--;
  }
};

// 找回密码表单提交
const handleForgotPasswordSubmit = async () => {
  if (!formData.newPassword || !formData.confirmNewPassword) {
    alert('请输入新密码并确认');
    return;
  }
  if (formData.newPassword !== formData.confirmNewPassword) {
    alert('两次输入的密码不一致');
    return;
  }
  const formdata = new FormData()
  formdata.append('account', formData.username)
  formdata.append('password', formData.newPassword)
  const judge = await resetac(formdata)
  if (judge == 1) { 
    success('您的新密码已重置成功');
    // 重置步骤
    currentStep.value = 1;
    // 重置表单数据
    resetFormData();
  }
  
};
</script>

<style scoped>
#reg_ret_box {
  background-image: url("../../public/about1.jpg");
  background-repeat: no-repeat;
  background-size: cover;
  width: 100vw;
  height: 100vh;
  background-position: center;
  display: flex;
  justify-content: center;
  align-items: center;
}

.form-container {
  max-width: 400px;
  width: 100%;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  background-color: white;
  margin-top: -200px; /* 你可以根据需要调整这个值 */
}

.form-selector {
  display: flex;
  justify-content: space-around;
  margin-bottom: 20px;
}

.selector-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  background-color: #f0f0f0;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.selector-btn.active {
  background-color: #6a11cb;
  color: white;
}

.selector-btn:hover {
  background-color: #ddd;
}

h2 {
  text-align: center;
  margin-bottom: 20px;
  color: #333;
}

.form-group {
  margin-bottom: 15px;
}

label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
  color: #555;
}

input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
  font-size: 14px;
}

.submit-btn,
.back-btn {
  width: 100%;
  padding: 10px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s ease;
}

.submit-btn {
  background-color: #6a11cb;
  color: white;
  margin-bottom: 10px;
}

.submit-btn:hover {
  background-color: #2575fc;
}

.back-btn {
  background-color: #f0f0f0;
  color: #333;
}

.back-btn:hover {
  background-color: #ddd;
}
</style>